/**
 * 商户维护
 * @constructor
 */
function Shop() {
}

Shop.init = function () {

    let Image = false;
    let Delete = false;
    let Update = false;
    //查询当前角色具备的菜单功能权限
    $.ajax({
        url: "/shop/getPermission",
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            $.each(data,function (i,button) {
                if (button.enDesc == "Insert"){
                    $("#toolbar").css("display","");
                }
                if (button.enDesc == "Image"){
                    Image = true;
                }
                if (button.enDesc == "Delete"){
                    Delete = true;
                }
                if (button.enDesc == "Update"){
                    $("#save3").css("display","");
                    $("#save4").css("display","");
                    $("#save5").css("display","");
                    Update = true;
                }
            });
        },
        error: function () {
            // alert("Error");
        }
    });

    //初始化富文本编辑器
    $('.summernote').summernote();

    //日期区间选择
    laydate.render({
        elem: '#text_CreateTime',
        theme: 'molv',
        type: 'date',
    });

    bindUserselect();
    bindServselect();
    bindProvinceCode("");
    bindTag();
    document.getElementById('text_ProvinceCode').onchange = function () {
        var provincecode = $("#text_ProvinceCode").val();
        if (provincecode != null && provincecode != "") {
            bindCityCode(provincecode, "");
        }
    }
    document.getElementById('text_CityCode').onchange = function () {
        var cityCode = $("#text_CityCode").val();
        if (cityCode != null && cityCode != "") {
            bindAreaCode(cityCode, "");
        }
    }
    $('#tableList').bootstrapTable({
        url: '/shop/tableSearch',
        method: 'post',
        striped: true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
        //search : "true",
        uniqueId: "id",
        pageList: [5, 10, 20, 50, 100],//可选择单页记录数
        pageSize: "10",
        pagination: true, // 是否分页
        sortable: true, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search: false,
        showColumns: true,
        showRefresh: true,
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
                //********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                //********
                //获取查询的对象，往下加入
                name: $('#search_Name').val(), // 请求时向服务端传递的参数
                state: $('#search_State').val(),
                typeofShop: $('#search_typeofShop').val(),
            };
            return query_params;
        },
        columns: [
            {
                //field: 'Number',//可不加
                title: '序号',//标题  可不加
                align: "center",
                width: 40,
                formatter: function (value, row, index) {
                    var pageSize = $('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber = $('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            {field: 'name', title: '商铺名称', align: 'center'},
            {
                field: 'typeofShop',
                title: '商铺类型',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    if (value == 1) {
                        optionHtml = "<span class=\"label label-danger\" style=\"cursor:pointer\"   title=\"直营\" >直营</span>";
                    } else if (value == 0) {
                        optionHtml = "<span class=\"label label-info\" style=\"cursor:pointer\"   title=\"加盟\">加盟</span>";
                    }
                    return optionHtml;

                }
            },
            {field: 'userName', title: '所属用户', align: 'center'},
            /*{
                title: '费率(%)',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    if (row.rate == 0 || row.rate == "" || row.rate == null) {
                        optionHtml= "0%";
                    }
                    else{
                        optionHtml=row.rate+"%";
                    }
                    return optionHtml;
                }
            },
            { field: 'charges', title: '提现手续费',align: 'center'},*/
            {field: 'createTime', title: '加盟时间', align: 'center'},
            {field: 'phone', title: '联系电话', align: 'center'},
            {field: 'address', title: '地址', align: 'center'},
            {field: 'cityName', title: '所在城市', align: 'center'},
            {field: 'shopType', title: '空间类型', align: 'center'},
            {field: 'notityCode', title: '公众号推送绑定码', align: 'center'},
            {field: 'notityOpenId', title: '店铺预约推送公众号', align: 'center'},
            {
                field: 'synopsis', title: '门店简介',align: 'center' ,
                formatter: function (value, row, index) {
                    console.log("row",row)
                    //var optionHtml = "<span class=\"label label-info\" style=\"cursor:pointer\" onclick='eidtSynopsis(" + JSON.stringify(row) + ")'  title=\"查看详情\" >查看详情</span>";
                    optionHtml ="<a class=\"btn btn-success btn-xs\"  href=\"/aboutus/editing/"+row.id+"\"><i class=\"fa fa-edit\"></i>查看详情</a>&nbsp&nbsp";
                    return optionHtml;
                }
            },
            {
                field: 'periphery', title: '周边配套',align: 'center' ,
                formatter: function (value, row, index) {
                    //var optionHtml = "<span class=\"label label-info\" style=\"cursor:pointer\" onclick='eidtPeriphery(" + JSON.stringify(row) + ")'  title=\"查看详情\" >查看详情</span>";
                    optionHtml ="<a class=\"btn btn-success btn-xs\"  href=\"/aboutus/editingzb/"+row.id+"\"><i class=\"fa fa-edit\"></i>查看详情</a>&nbsp&nbsp";
                    return optionHtml;

                }
            },
            {
                field: 'reservation', title: '预定须知',align: 'center' ,
                formatter: function (value, row, index) {
                    //var optionHtml = "<span class=\"label label-info\" style=\"cursor:pointer\" onclick='eidtReservation(" + JSON.stringify(row) + ")'  title=\"查看详情\" >查看详情</span>";
                    optionHtml ="<a class=\"btn btn-success btn-xs\"  href=\"/aboutus/editingyd/"+row.id+"\"><i class=\"fa fa-edit\"></i>查看详情</a>&nbsp&nbsp";
                    return optionHtml;

                }
            },
            {field: 'endTime', title: '营业结束时间', align: 'center'},
            {
                title: '状态',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    if (row.state == 0) {
                        optionHtml = "<span class=\"label label-danger\" style=\"cursor:pointer\"   title=\"未激活\" >未激活</span>";
                    } else if (row.state == 1) {
                        optionHtml = "<span class=\"label label-info\" style=\"cursor:pointer\"   title=\"已激活\">已激活</span>";
                    }
                    return optionHtml;

                }
            },
            {
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    if (Image){
                        optionHtml = "<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"image\")' title=\"图片\" ><i class=\"fa fa-search\"></i>图片</a>";
                    }
                    if (Update){
                        optionHtml = optionHtml+" <a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"edit\")' title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a>";
                    }
                    if (Delete){
                        optionHtml = optionHtml + " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"delete\")'  title=\"删除\"><i class=\"fa fa-remove\"></i>删除</a>"
                    }
                    return optionHtml;

                }
            }
        ]
    });
}

//查询方法****************************
function doSearch() {
    $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
}

//重置****************************
function doRest() {
    $("#search_Name").val("");
    $("#search_State").val("");
    $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
}

//增加方法****************************
var Action = "";
var Id = 0;
var pxt = "/shop"; //控制器名称
function addRecord() {
    Id = 0;
    Action = "add";
    $("#myform")[0].reset();
    $("#save").removeAttr("disabled");
    $("#text_ClientNo").removeAttr("readonly");

}

//增加/修改数据保存****************************
function saveRecord() {
    //创建传递的参数
    var postdata = {
        id: Id,
        action: Action,
        name: $("#text_Name").val(),
        rate: $("#text_Rate").val(),
        charges: $("#text_Charges").val(),
        address: $("#text_Address").val(),
        phone: $("#text_Phone").val(),
        userId: $("#com_UserId").val(),
        lng: $("#text_Lng").val(),
        lat: $("#text_Lat").val(),
        remark: $("#text_Remark").val(),
        state: $("#com_State").val(),
        createTime: $("#text_CreateTime").val(),
        types: $("#com_type").val(),
        parentId: $("#text_Superior").val(),
        shopType: $("#text_ShopType").val(),
        tags: $("#text_Tags").val(),
        space: $("#text_Space").val(),
        provinceCode: $("#text_ProvinceCode").val(),
        cityCode: $("#text_CityCode").val(),
        areaCode: $("#text_AreaCode").val(),
        startTime: $("#text_StartTime").val(),
        endTime: $("#text_EndTime").val(),
        typeofShop: $("#typeofShop").val(),
    };
    // console.log(JSON.stringify(postdata));
    //发送异步请求到后台保存用户数据
    $.ajax({
        url: pxt + "/save",
        type: "post",
        data: JSON.stringify(postdata),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}

//操作相关方法****************************
function actionRecord(data, type) {
    if (type == "edit") {
        //修改
        Id = data.id;
        Action = "edit";
        //  $("#text_ClientNo").attr("readonly", "true");
        $("#myform")[0].reset();
        $("#save").removeAttr("disabled");
        WriteData(data)
        $('#myModalAdd').modal('show')
    } else if (type == "image") {
        //修改
        Id = data.id;
        Action = "image";
        //  $("#text_ClientNo").attr("readonly", "true");
        $("#myform2")[0].reset();
        // $("#save").removeAttr("disabled");
        $("#photourl").removeAttr("src");
        getImage();
        $('#myModalAdd2').modal('show')
    } else if (type == "delete") {
        //删除
        swal({
            title: "确认是否删除",
            text: "是否确认要删除该条记录？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
            //点击删除之后此处进行传递后台
            $.ajax({
                type: "delete",
                url: pxt + "/deleteById/" + data.id,
                dataType: "json",
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code == "200") {
                        doSearch();
                        swal("删除成功!", "请继续操作", "success");
                    } else {
                        swal("删除失败!", "请重试", "error");
                    }
                }
            });

        });
    } else if (type == "change") {
        //状态变更
        var alertstr = "未知操作";
        var state = 0;
        if (data.state == 0) {
            alertstr = "是否将该用户变更为：激活？";
            state = 1;
        } else if (data.state == 1) {
            alertstr = "是否将该用户变更为：未激活？";
            state = 0;
        }
        swal({
            title: "状态变更",
            text: alertstr,
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
            //点击删除之后此处进行传递后台
            //创建传递的参数
            var postdata = {
                action: "change",
                id: data.id,
                state: state,
            };
            $.ajax({
                url: pxt + "/save",
                type: "post",
                data: JSON.stringify(postdata),
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    if (data.code === "200") {
                        $('#myModalAdd').modal('hide')
                        doSearch();
                        swal("状态已变更!", "请继续操作", "success");
                    } else {
                        swal("操作失败!", "请重试", "error");
                    }
                }
            })

        });
    }
}

//给控件赋值****************************
function WriteData(data) {
    bindProvinceCode(data.provinceCode);
    bindCityCode(data.provinceCode, data.cityCode);
    bindAreaCode(data.cityCode, data.areaCode);
    var a = $("#text_ProvinceCode").val();
    var b = $("#text_CityCode").val();
    var c = $("#text_AreaCode").val();
    console.log(data.provinceCode + "----" + data.cityCode + "-----" + data.areaCode);
    console.log(a);
    console.log(b);
    console.log(c);
    $("#text_Name").val(data.name);
    $("#text_Rate").val(data.rate);
    $("#text_Charges").val(data.charges);
    $("#text_Address").val(data.address);
    $("#text_Phone").val(data.phone);
    $("#com_UserId").val(data.userId);
    $("#text_Lng").val(data.lng);
    $("#text_Lat").val(data.lat);
    $("#text_Remark").val(data.remark);
    $("#com_State").val(data.state);
    $("#text_CreateTime").val(data.createTime);
    $("#com_type").val(data.types);
    $("#text_Superior").val(data.parentId);
    $("#text_ShopType").val(data.shopType);
    $("#text_Tags").val(data.tags);
    $("#text_Space").val(data.space);
    $("#text_StartTime").val(data.startTime);
    $("#text_EndTime").val(data.endTime);
    $("#typeofShop").val(data.typeofShop);
}

//绑定下拉****************************
function bindUserselect() {

    $.ajax({
        url: "/shop/getShopUser",
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var ddl1 = $("#com_UserId");
            //删除节点
            $("#com_UserId option").remove();

            //转成Json对象
            var result = eval(data.data);
            var opt1 = $("<option value=''></option>").text("--请选择所属用户--").val("");

            ddl1.append(opt1);

            //循环遍历 下拉框绑定
            $(result).each(function (key) {
                //添加option 对应Json对象名称
                opt1 = $("<option></option>").text(result[key].userName).val(result[key].userID);

                ddl1.append(opt1);

            });
        },
        error: function () {
            // alert("Error");
        }
    });

}

function bindServselect() {
    $.ajax({
        url: "/shop/getServUser",
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var ddl1 = $("#text_Superior");
            //删除节点
            $("#text_Superior option").remove();
            //转成Json对象
            var result = eval(data.data);
            var opt1 = $("<option value=''></option>").text("--请选择所属服务商--").val("");
            ddl1.append(opt1);
            //循环遍历 下拉框绑定
            $(result).each(function (key) {
                //添加option 对应Json对象名称
                opt1 = $("<option></option>").text(result[key].userName).val(result[key].userID);
                ddl1.append(opt1);
            });
        },
        error: function () {
            // alert("Error");
        }
    });

}

//标签下拉绑定
function bindTag() {
    selectMultip.register();
    $.ajax({
        url: "/tag/getAllTag",
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            console.log("回调json为：", res)
            console.log("回调数据为：", res.data)
            var data = []
            var obj = {};
            obj.value ="";
            obj.text ="可多选，再次点击即可取消";
            data.push(obj);
            for (var i = 0; i < res.data.length; i++) {
                console.log("标签名为：",res.data[i].tagName)
                var obj = {};
                obj.value =res.data[i].tagName;
                obj.text =res.data[i].tagName;
                data.push(obj);
            }
            // for (var a in res.data) {
            //     console.log("标签名为：",a.tagName)
            //     var obj = {};
            //     obj.value = a.tagName;
            //     obj.text = a.tagName;
            //     data.push(obj);
            // }
            selectMultip.reload("text_Tags", data, "标签名");
        },
    })
}

//上传****************************
function ImportShipmentStatusList() {
    var timestamp = new Date().getTime();
    var upname = "fuImportMultipleShipmentStatus";
    console.log(timestamp);
    console.log("upname:" + $("#" + upname).val());
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: '/room/uploadImages?type=1&id=' + Id,
        secureuri: false,
        fileElementId: upname,
        dataType: 'text',
        success: function (data, status) {
            //console.log(data);
            // $("#photourl").attr("src", "/images/" + data);
            // $("#imgURL").attr("value", data);
            getImage();
        },
        error: function (data, status, e) {
            alert("上传失败");
        }

    });
}

function getImage() {

    $.ajax({
        url: "/room/getRoomImages?type=1&roomId=" + Id,
        type: "get",
        //data:JSON.stringify(postdata),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            console.log(data);
            $.each(data, function (i, val) { //两个参数，第一个参数表示遍历的数组的下标，第二个参数表示下标对应的值
                // console.log(i + '```````' + val.url);
                $("#photourl").attr("src", "/images/" + val.url);
            });
        }
    });
}

function bindProvinceCode(type) {
    $.ajax({
        url: "/city/getProvinceCode",
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var ddl1 = $("#text_ProvinceCode");
            //删除节点
            $("#text_ProvinceCode option").remove();
            //转成Json对象
            var result = eval(data.data);
            var opt1 = $("<option value=''></option>").text("--省级编码--").val("");
            ddl1.append(opt1);
            //循环遍历 下拉框绑定
            $(result).each(function (key) {
                //添加option 对应Json对象名称
                if (result[key].code == type) {
                    opt1 = $("<option selected></option>").text(result[key].city).val(result[key].code);
                } else {
                    opt1 = $("<option></option>").text(result[key].city).val(result[key].code);
                }
                ddl1.append(opt1);
            });
        },
        error: function () {
            // alert("Error");
        }
    });
}

function bindCityCode(provincecode, type) {
    $.ajax({
        url: "/city/getCityCode?provincecode=" + provincecode,
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var ddl1 = $("#text_CityCode");
            //删除节点
            $("#text_CityCode option").remove();
            //转成Json对象
            var result = eval(data.data);
            var opt1 = $("<option value=''></option>").text("--城市编码--").val("");
            ddl1.append(opt1);
            //循环遍历 下拉框绑定
            $(result).each(function (key) {
                //添加option 对应Json对象名称
                if (result[key].code == type) {
                    opt1 = $("<option selected></option>").text(result[key].city).val(result[key].code);
                } else {
                    opt1 = $("<option></option>").text(result[key].city).val(result[key].code);
                }
                ddl1.append(opt1);
            });
        },
        error: function () {
            // alert("Error");
        }
    });
}

function bindAreaCode(provincecode, type) {
    $.ajax({
        url: "/city/getAreaCode?provincecode=" + provincecode,
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var ddl1 = $("#text_AreaCode");
            //删除节点
            $("#text_AreaCode option").remove();
            //转成Json对象
            var result = eval(data.data);
            var opt1 = $("<option value=''></option>").text("--区县编码--").val("");
            ddl1.append(opt1);
            //循环遍历 下拉框绑定
            $(result).each(function (key) {
                //添加option 对应Json对象名称
                if (result[key].code == type) {
                    opt1 = $("<option selected></option>").text(result[key].city).val(result[key].code);
                } else {
                    opt1 = $("<option></option>").text(result[key].city).val(result[key].code);
                }
                ddl1.append(opt1);
            });
        },
        error: function () {
            // alert("Error");
        }
    });
}

//门店介绍****************************
/*
function eidtSynopsis(data) {
    Id = data.id;
    Action="edit";
    $("#save").removeAttr("disabled");
    //$('#myModalAdd3').modal('show');
    AddMenus();
    $('.summernote').eq(0).code(data.synopsis);
}
//修改门店介绍***********************
function addRecord3() {
    let postdata = {
        id : Id,
        synopsis:$('.summernote').eq(0).code(),
    }
    $.ajax({
        url:pxt+"/update",
        type:"post",
        data:JSON.stringify(postdata),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}

//周边配套****************************
function eidtPeriphery(data) {
    Id = data.id;
    Action="edit";
    $("#save").removeAttr("disabled");
    $('#myModalAdd4').modal('show');
    $('.summernote').eq(1).code(data.periphery);
}
//修改周边配套***********************
function addRecord4() {
    let postdata = {
        id : Id,
        periphery:$('.summernote').eq(1).code(),
    }
    $.ajax({
        url:pxt+"/update",
        type:"post",
        data:JSON.stringify(postdata),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}
//预定须知****************************
function eidtReservation(data) {
    Id = data.id;
    Action="edit";
    $("#save").removeAttr("disabled");
    $('#myModalAdd5').modal('show');
    $('.summernote').eq(2).code(data.reservation);
}
//修改预定须知***********************
function addRecord5() {
    let postdata = {
        id : Id,
        reservation:$('.summernote').eq(2).code(),
    }
    $.ajax({
        url:pxt+"/update",
        type:"post",
        data:JSON.stringify(postdata),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}
*/

//*****************************************************************************************
